/**
 *@author qzg
 *@description joi参数校验中间件
 *@createDate 2022年07月05日 19:11:27
 */
import { PartialSchemaMap } from 'joi'
import { Middleware } from 'koa'
import Joi from '../utils/joi'
//此处的validate是一个中介，执行validate(实际上只是为了传递一个rules参数)真正返回的validateParams才是要处理的中间件函数
//如果不把validate当作中间函数而是直接定义为中间件函数，rule就无法传递因为默认的中间件是function(ctx,next){}会造成类型不匹配
const validate = (rule: PartialSchemaMap) => {
  const validateParams: Middleware = async (ctx, next) => {
    let data: any
    if (ctx.request.method === 'GET' || ctx.request.method === 'DELETE') {
      data = ctx.request.query
      const schema = Joi.object(rule)
      await schema.validateAsync(data)
    } else if (['POST', 'PUT', 'PATCH'].indexOf(ctx.request.method) != -1) {
      data = ctx.request.body

      const schema = Joi.object(rule)
      await schema.validateAsync(data)
    }

    await next()
  }
  return validateParams
}
export default validate
